package com.lzw.breezeNovel.webApp.service.impl.novel;

import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.model.entity.pojo.novel.ReadTime;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.webApp.mapper.novel.ReadTimeMapper;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.service.novel.ReadTimeService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.novel.impl
 * @date 2025/3/6
 * @description 用户阅读的实现类
 */
@Service
@SuppressWarnings("all")
public class ReadTimeServiceImpl implements ReadTimeService {

    /**
     * 注入阅读时间的mapper
     */
    @Autowired
    private ReadTimeMapper readTimeMapper;

    /**
     * 注入用户信息的mapper
     */
    @Autowired
    private UserInfoMapper userInfoMapper;


    /**
     * 保存用户阅读时间
     * @param readTime
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveReadTime(@NotNull String dayTime) {
        //获取当前用户
        UserInfo userInfo = getUserInfo();
        //根据用户id查询阅读时间
        String readTimes = readTimeMapper.selectByUserId(userInfo.getUserId());
        //创建阅读时间对象
        ReadTime readTime = new ReadTime();
        //设置用户id
        readTime.setUserId(userInfo.getUserId());
        if (readTimes == null) {
            //设置阅读时间
            readTime.setDayTime(dayTime);
            //设置总阅读时间
            readTime.setTotalTime(dayTime);
            //保存阅读时间
            readTimeMapper.insert(readTime);
        }else {
            //更新阅读时间
            readTime.setDayTime(readTimes + dayTime);
            //更新总阅读时间
            readTime.setTotalTime(readTimes + dayTime);
            //更新阅读时间
            readTimeMapper.updateByUserId(readTime);
        }

    }

    /**
     * 获取用户的阅读时间
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public String getReadTime() {
        //获取当前用户
        UserInfo userInfo = getUserInfo();
        //根据用户id查询阅读时间
        String readTime = readTimeMapper.selectByUserId(userInfo.getUserId());
        return readTime;
    }

    /**
     * 获取用户信息
     */
    @Transactional(readOnly = true)
    public UserInfo getUserInfo() {
        //获取当前用户
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        String phone = loginUser.getPhone();
        //根据手机号查询用户信息
        UserInfo userInfo = userInfoMapper.selectByPhone(phone);
        return userInfo;
    }

}
